<template>
  <div class="container">
    <el-card style="position: relative">
      <RouterHeader :title="titleStr()"></RouterHeader>
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleFormRef"
        label-width="140px"
        label-position="right"
      >
        <el-row :gutter="20" class="form-single-info">
          <el-col :span="20">
            <div class="title"><h5>基本信息</h5></div>
            <el-row style="margin-left: 70px">
              <el-col :span="24">
                <el-descriptions>
                  <el-descriptions-item label="所属项目:">
                    <el-button
                      @click="correlation"
                      link
                      type="primary"
                      v-if="route.query.name === '1'"
                      >点此关联</el-button
                    >
                    <el-button v-else link>{{ form.projectName }}</el-button>
                  </el-descriptions-item>
                </el-descriptions>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input
                    class="input-item"
                    v-model="form.projectName"
                    placeholder="请输入"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="业主单位" prop="enterpriseName">
                  <el-input
                    class="input-item"
                    v-model="form.enterpriseName"
                    placeholder="请输入"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目联系人电话" prop="enterprisePhone">
                  <el-input
                    class="input-item"
                    v-model="form.enterprisePhone"
                    placeholder="请输入"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目联系人" prop="enterprisePerson">
                  <el-input
                    class="input-item"
                    v-model="form.enterprisePerson"
                    placeholder="请输入"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="监督部门" prop="superviseDept">
                  <el-select
                    class="input-item"
                    v-model="form.superviseDept"
                    placeholder="请选择"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    disabled
                  >
                    <el-option
                      v-for="item in superviseDeptOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="审批部门" prop="approvalDept">
                  <el-select
                    class="input-item"
                    v-model="form.approvalDept"
                    placeholder="请选择"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    disabled
                  >
                    <el-option
                      v-for="item in approvaDeptOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="行业" prop="industry">
                  <el-select
                    v-model="form.industry"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    placeholder="请输入"
                    style="width: 240px"
                    disabled
                  >
                    <el-option
                      v-for="item in industryDownOption"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="8">
                <el-form-item label="项目属性" prop="projectProperty">
                  <el-input
                    class="input-item"
                    v-model="form.projectProperty"
                    placeholder="请输入"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="业务类型" prop="businessType">
                  <el-cascader
                    v-model="businessType"
                    ref="ref_business"
                    :options="businesstypeTree"
                    :props="businesstProps"
                    :show-all-levels="true"
                    disabled
                    class="custom-cascader"
                  ></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所在地区" prop="address">
                  <el-cascader
                    v-model="form.address"
                    :options="areaList"
                    :props="areaCodeprops"
                    ref="ref_areaCodes"
                    :show-all-levels="true"
                    disabled
                  ></el-cascader>
                </el-form-item>
              </el-col>

              <!-- <el-col :span="8">
                <el-form-item label="优先级" prop="priority">
                  <el-select
                    v-model="form.priority"
                    clearable
                    placeholder="请选择"
                    style="width: 240px"
                    disabled
                  >
                    <el-option
                      v-for="item in priorityOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="24">
                <el-form-item label="项目简述" prop="projectBriefly">
                  <el-input
                    class="input-item"
                    type="textarea"
                    :autosize="{ minRows: 2 }"
                    show-word-limit
                    v-model="form.projectBriefly"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目备注" prop="projectRemark">
                  <el-input
                    class="input-item"
                    type="textarea"
                    :autosize="{ minRows: 2 }"
                    show-word-limit
                    v-model="form.projectRemark"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="title">
              <h5>合同信息</h5>
            </div>
            <el-row>
              <el-col :span="12">
                <el-form-item label="合同名称" prop="contractName">
                  <el-input
                    class="input-item"
                    v-model="form.contractName"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!-- <el-form-item label="合同金额" prop="contractAmount">
                  <el-input
                    type="number"
                    class="input-item"
                    v-model="form.contractAmount"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  >
                    <template #append> 万元 </template>
                  </el-input>
                </el-form-item> -->
                <el-form-item label="项目总投额" prop="contractAllAmount">
                  <el-input
                    class="input-item"
                    v-model="form.contractAllAmount"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  >
                    <template #append> 万元 </template>
                  </el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合同期限" prop="contractDate">
                  <el-date-picker
                    v-model="contractDate"
                    type="daterange"
                    range-separator="To"
                    start-placeholder="请选择"
                    end-placeholder="请选择"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :disabled-date="disabledDate"
                    :disabled="isDisabled()"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="付款方式">
                  <el-input
                    class="input-item"
                    v-model="form.paymentMethod"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col
                :span="8"
                v-if="route.query.name === '3' && route.query.contractStatus"
              >
                <el-form-item label="签订时间" prop="signTime">
                  <el-date-picker
                    v-model="form.signTime"
                    type="datetime"
                    range-separator="To"
                    start-placeholder="请选择"
                    end-placeholder="请选择"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :disabled-date="disabledDate"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                
              </el-col>
              <el-col :span="12">
                
              </el-col>

              <el-col :span="24">
                <el-form-item label="业务类型及金额" prop="businessTypeList">
                  <!-- <el-cascader
                    v-model="form.businessTypeList"
                    ref="ref_business"
                    :options="businesstypeTree"
                    :props="businesstProps"
                    :show-all-levels="true"
                    :disabled="isDisabled()"
                  ></el-cascader> -->

                  <el-select
                    v-model="form.businessTypeList"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  >
                    <el-option
                      v-for="item in businessOptions"
                      :key="item.id"
                      :label="item.businessName"
                      :value="item.id"
                    />
                  </el-select>


                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                <el-form-item label="是否盖章" prop="isStamped">
                  <el-radio-group
                    v-model="form.isStamped"
                    :disabled="isDisabled()"
                  >
                    <el-radio :label="0">是</el-radio>
                    <el-radio :label="1">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="8" v-if="form.isStamped === 0">
                <el-form-item label="盖章份数" prop="stampCount">
                  <el-input
                    class="input-item"
                    v-model="form.stampCount"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.isStamped === 0">
                <el-form-item label="盖章类型">
                  <el-select
                    v-model="form.stampTypeList"
                    placeholder="请选择"
                    multiple
                    filterable
                    allow-create
                    default-first-option
                    :reserve-keyword="false"
                    :disabled="isDisabled()"
                  >
                    <el-option
                      v-for="item in whatOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <!-- :flag="true" -->
                <el-form-item label="合同附件">
                  <fileupload
                    @update:modelValue="handleContractValueFile"
                    :modelValue="form.fileListBefor"
                    :isShowTip="
                      route.query.name === '3' && route.query.contractStatus
                        ? false
                        : true
                    "
                    :flag="
                      (route.query.name === '3' &&
                        route.query.contractStatus) ||
                      route.query.name === '6' ||
                      route.query.name === '5'
                        ? true
                        : false
                    "
                  ></fileupload>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row
              v-if="route.query.name === '3' && route.query.contractStatus"
            >
              <el-col :span="24">
                <el-form-item label="附件">
                  <fileupload
                    @update:modelValue="handleModelValueTaskFile"
                    :modelValue="form.fileListAfter"
                  ></fileupload>
                </el-form-item>
              </el-col>
            </el-row>

            <div
              v-if="
                route.query.name === '2' ||
                route.query.name === '5' ||
                route.query.name === '6' ||
                (route.query.name === '3' && !route.query.contractStatus)
              "
            >
              <div class="title"><h5>项目审批进度</h5></div>
              <el-timeline style="max-width: 600px">
                <el-timeline-item
                  v-for="(activity, index) in activities"
                  :key="index"
                  :color="activity.color"
                  :timestamp="activity.updateTime"
                >
                  <div style="display: flex; align-items: center">
                    <img :src="url + activity.avatar" class="user-avatar" />
                    <span
                      style="
                        font-size: 14px;
                        font-weight: 500;
                        margin-left: 5px;
                      "
                    >
                      {{ activity.username }} ({{
                        activity.checkHisResult === "2" ? "未审核" : "已审核"
                      }})
                      {{
                        activity.zuofei === "0"
                          ? " _作废"
                          : activity.zuofei === "null"
                          ? ""
                          : ""
                      }}
                      :</span
                    >
                    <span
                      style="
                        font-size: 14px;
                        font-weight: 400;
                        margin-left: 5px;
                      "
                    >
                      {{ activity.opinion }}</span
                    >
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>

            <el-row
              v-if="
                route.query.name === '1' ||
                route.query.name === '2' ||
                route.query.name === '6'
              "
            >
              <el-col :span="24">
                <el-form-item label="审批方式">
                  <el-radio-group
                    v-model="form.processCheckBo.checkType"
                    :disabled="isDisabled()"
                  >
                    <el-radio :label="0">自由审批</el-radio>
                    <el-radio :label="1">逐级审批</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <!-- v-if="
                  !(approval.value !== 1 && form.keepCheck === '1')
                " -->
              <el-col :span="24">
                <el-form-item
                  label="审批流程"
                  style="padding: 20px 0"
                  v-if="
                    (route.query.name === '6' &&
                      form.processCheckBo.checkType === 0 &&
                      keepCheck === '1') ||
                    (route.query.name !== '6' && keepCheck === '1')
                  "
                >
                  <approver
                    :approverList="form.processCheckBo.checkPeopleIds"
                    :typeId="3"
                    :isEdit="!!$route.query.projectId"
                    @handleChooseapprover="handleChooseapprover"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item
                  label="抄送"
                  style="padding: 20px 0"
                  v-if="
                    (route.query.name === '6' &&
                      form.processCheckBo.checkType === 0 &&
                      keepCheck === '1') ||
                    (route.query.name !== '6' && keepCheck === '1')
                  "
                >
                  <approver
                    :typeId="3"
                    :approverList="form.processCheckBo.copyFor"
                    :isCc="true"
                    @handleChooseapprover="handleChooseapproverCc"
                  ></approver>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="route.query.name === '6' || route.query.name === '5'">
              <el-col :span="24">
                <el-form-item label="审批意见" prop="projectImplementation">
                  <el-input
                    class="input-item"
                    type="textarea"
                    :autosize="{ minRows: 2 }"
                    show-word-limit
                    v-model="form.approvalOpinions"
                    placeholder="请输入"
                    :disabled="
                      route.query.name === '5' || route.query.name === '3'
                    "
                  ></el-input>
                </el-form-item>
                <el-form-item label="审批附件/图片">
                  <fileupload
                    @update:modelValue="handleModelValueFile"
                    :modelValue="form.fileList"
                  ></fileupload>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item
                  label="审批决定"
                  v-if="form.processCheckBo.checkType !== 1"
                >
                  <el-radio-group
                    v-model="keepCheck"
                    class="ml-4"
                    :disabled="route.query.name === '5' ? true : false"
                  >
                    <el-radio label="0" size="large">完成审批</el-radio>
                    <el-radio label="1" size="large">继续审批</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item v-if="shouldShowButton">
              <div style="width: 100%; display: flex; justify-content: center">
                <el-button @click="resetForm(ruleFormRef)">
                  {{ cancelButtonText }}
                </el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                  {{ submitButtonText }}
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-dialog v-model="dialogTableVisible" title="关联项目" width="1000">
        <PropTable
          :columns="column"
          :data="form.gridData"
          :total="total"
          :show="false"
          @reset="reset"
          @onSubmit="onSubmit"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
          @exportExcelAction="exportExcelAction"
        >
          <template v-slot:projectCreateTime="scope">
            <div v-if="!useEmpty(scope.row.projectCreateTime)">
              {{ formatDate(scope.row.projectCreateTime) }}
            </div>
          </template>
          <template v-slot:operation="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleClick(scope.row)"
            >
              选择
            </el-button>
          </template>
        </PropTable>
      </el-dialog>
      <el-dialog
        title="新增成员"
        v-model="detailsvisible"
        :before-close="handleClose"
        width="60%"
        style="background: #fff; height: 100%; margin-bottom: 20px"
      >
        <selectPeople
          :projectUserDtoList="form.projectUserDtoList"
          @selectTable="selectTable"
          @deleteTable="deleteTable"
          @submitSelectForm="submitSelectForm"
          @handleSelectClose="handleSelectClose"
        ></selectPeople>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import RouterHeader from "@/components/RouterHeader";
import { reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import fileupload from "@/components/FileUpload";
import approver from "@/components/Approve/approver";
import PropTable from "@/components/Table/PropTable/index.vue";
import {
  approvalLists,
  addContractApi,
  contractDetail,
  uploadAttachments,
  updateContractApi,
} from "@/api/contract/index";

import { approvalProcessApi } from "@/api/approvalManagement/approvaType";
import {
  approvalList,
  approvalQuery,
  industryDownApi,
} from "@/api/project/approval";

import { 
  businessTypeList, 
  getbusinessTypeList,
  location,
  getbusinessTypeDic
} from "@/api/project/conversion";
import { getUserProfile } from "@/api/system/user";
import { ElMessage } from "element-plus";
import { useEmpty, formatDate } from "@/utils/index";
import { taskDelivery } from "@/api/approvalManagement/approvaType.js";
let url = import.meta.env.VITE_APP_BASE_API;
const keepCheck = ref("1");
const route = useRoute();
const router = useRouter();
const dialogTableVisible = ref(false); // dialog关联对话框
const detailsvisible = ref(false); // 添加审批人对话框
const activities = ref([]);
// 优先级
const priorityOptions = [
  {
    value: "1",
    label: "最高",
  },
  {
    value: "2",
    label: "较高",
  },
  {
    value: "3",
    label: "较低",
  },
  {
    value: "4",
    label: "最低",
  },
];
const unitsList = [
  { value: "0", label: "元" },
  { value: "1", label: "万元" },
  { value: "2", label: "亿元" },
];

// 监督部门
const superviseDeptOptions = [
  {
    id: "1",
    label: "住建",
  },
  {
    id: "2",
    label: "采购办",
  },
  {
    id: "3",
    label: "水利",
  },
  {
    id: "4",
    label: "交通",
  },
  {
    id: "5",
    label: "发改",
  },
  {
    id: "6",
    label: "环保",
  },
  {
    id: "7",
    label: "其他",
  },
];
// 审批部门
const approvaDeptOptions = [
  {
    id: "1",
    label: "生态环境局",
  },
  {
    id: "2",
    label: "行政审批局",
  },
  {
    id: "3",
    label: "经济发展局",
  },
  {
    id: "4",
    label: "发展改革局",
  },
  {
    id: "5",
    label: "其他",
  },
];

const whatOptions = [
  {
    id: "1",
    label: "项目公章",
  },
  {
    id: "2",
    label: "项目财务章",
  },
  {
    id: "3",
    label: "成果章",
  },
  {
    id: "4",
    label: "许平人员章",
  },
  {
    id: "5",
    label: "赵冲人员章",
  },
  {
    id: "6",
    label: "牛天敏人员章",
  },
  {
    id: "7",
    label: "李彦文人员章",
  },
  {
    id: "8",
    label: "合同章",
  },
  {
    id: "9",
    label: "法人章",
  },
];

const hasButtonSave = ref(false);

// 1.按钮保存隐藏
const hasButton = () => {
  if (route.query.name === "3" || route.query.name === "5") {
    hasButtonSave.value = false;
  } else {
    hasButtonSave.value = true;
  }
};

const businessType = ref([]);

//   attachments: [], // 合同附件

// 表单对象
const form = reactive({
  projectName: "", // 基本信息项目名称
  enterpriseName: "", //企业名称
  enterprisePhone: "", //项目联系人电话
  enterprisePerson: "", //项目联系人
  industry: [], // 行业
  projectProperty: "", //项目属性
  businessTypeList: [], //合同信息
  projectId: "",
  address: "", //所在地区
  projectBriefly: "",
  projectRemark: "",
  approvalDept: [], // 审批部门
  superviseDept: [], // 监督部门
  contractName: "", // 合同名称
  contractAmount: "", //合同金额
  signTime: "", //签订时间
  paymentMethod: "",
  isStamped: 1,
  stampCount: "",
  stampTypeList: [],
  businessType: "",
  gridData: [], //  关联项目表格
  processCheckBo: {
    checkPeopleIds: [], //审核人id列表
    copyFor: [], //抄送人id列表
    checkType: 1, //逐级审批
  },
  approvalOpinions: "", // 审批意见
  //   filleList:[],
  processCheckHistoryId: "",
  approvalFiles: [],
  amountUnit: "",
  fileListBefor: [], //合同审批之前的附件
  fileListAfter: [], //
  fileList: [], //审批意见的附件
  contractAllAmount: "",
});
// 表单验证
const rules = reactive({
  contractName: [
    {
      required: true,
      message: "请输入合同名称",
      trigger: "blur",
    },
  ],
  contractAmount: [
    {
      required: true,
      message: "请输入合同金额",
      trigger: "blur",
    },
  ],
  businessTypeList: [
    {
      required: true,
      message: "请选择业务类型",
      trigger: "change",
    },
  ],
  signTime: [
    {
      type: "daterange",
      required: true,
      message: "请选择签订时间",
      trigger: "change",
    },
  ],
});

const contractDate = ref();

// 计算属性来决定按钮是否显示
const shouldShowButton = computed(() => {
  const name = route.query.name;
  const contractStatus = route.query.contractStatus;

  // 如果 name 是 "3" 但 contractStatus 存在，则显示按钮
  if (name === "3" && contractStatus) {
    return true;
  }

  // 如果 name 是 "6"，则显示按钮
  if (name === "5" || name === "3") {
    return false;
  }

  // 其他情况下不显示按钮
  return true;
});

// 动态计算取消按钮的文本
const cancelButtonText = computed(() => {
  return route.query.name === "6" ? "驳回" : "取消";
});

// 动态计算提交按钮的文本
const submitButtonText = computed(() => {
  return route.query.name === "6" ? "通过" : "确认";
});

// 2.控制表单项是否只读
const isDisabled = () => {
  if (
    route.query.name === "6" ||
    route.query.name === "5" ||
    route.query.name === "3"
  ) {
    return (disabled.value = true);
  } else {
    return (disabled.value = false);
  }
};

const titleStr = () => {
  if (route.query.name === "1") {
    return "新建合同";
  } else if (route.query.name === "2") {
    return "编辑合同";
  } else if (route.query.name === "3" && route.query.contractStatus) {
    return "上传附件";
  } else if (route.query.name === "3") {
    return "详情合同";
  } else {
    return "审批合同";
  }
};
// 禁用今天之前的日期
const disabledDate = (time) => {
  // // 使用JavaScript的Date对象来判断
  // const today = new Date(new Date().setHours(0, 0, 0, 0));
  // const currentTime = today.getTime();
  // // 将time参数转换为时间戳，方便比较
  // const timeValue = time.getTime();
  // // 如果时间戳小于当前时间戳，则返回true，表示该日期被禁用
  // return timeValue < currentTime;
  return false;
};

const btnText = ref("");
// 按钮
const btnTextTab = () => {
  if (route.query.name === "3" && route.query.task === "2") {
    btnText.value = "提交";
  } else if (route.query.name === "6") {
    btnText.value = "通过";
  } else {
    btnText.value = "确认";
  }
};
const industryDownOption = ref([]);
// 获取行业下拉列表
const getindustryDown = async () => {
  const res = await industryDownApi();
  if (res.code === 200) {
    industryDownOption.value = res.data;
  }
};
btnTextTab();
// 获取用户信息
const getUser = async () => {
  const res = await getUserProfile();
  if (res.code === 200 && res.data) {
    form.taskExecutor = res.data.nickName;
    form.createBy = res.data.userId;
  }
};
const disabled = ref(true);

// 添加附件
// const handleModelValueFile = (val, result, operationType) => {
//   if (operationType === "success") {
//     if (result) {
//       if (form.attachments === null) {
//         form.attachments = [];
//         form.attachments.push(result);
//       } else {
//         form.attachments.push(result);
//       }
//     }
//   } else if (operationType === "delete") {
//     form.attachments.splice(result, 1);
//   }
// };

// 合同附件
const handleContractValueFile = (val, result, operationType) => {
  if (operationType === "success") {
    if (result) {
      form.fileListBefor = [];
        result.forEach((item)=>{
          form.fileListBefor.push(item);
        });
    }
  } else if (operationType === "delete") {
    form.fileListBefor.splice(result, 1);
  }
};

// 附件
const handleModelValueTaskFile = (val, result, operationType) => {
  if (operationType === "success") {
    if (result) {
      form.fileListAfter = [];
        result.forEach((item)=>{
          form.fileListAfter.push(item);
        });
    }
  } else if (operationType === "delete") {
    form.fileListAfter.splice(result, 1);
  }
};

// 审批意见的附件
const handleModelValueFile = (val, result, operationType) => {
  if (operationType === "success") {
    if (result) {
      form.fileList = [];
        result.forEach((item)=>{
          form.fileList.push(item);
        });
    }
  } else if (operationType === "delete") {
    form.fileList.splice(result, 1);
  }
};

// 业务类型树形列表
const businesstypeTree = ref([]);
// 业务类型props配置
const businesstProps = {
  value: "id",
  label: "businessName",
  children: "children",
  checkStrictly: true,
  multiple: true,
};
// 获取查询业务类型树形列表
const businessTypeOptions = async () => {
  const response = await businessTypeList();
  if (response.code === 200 && response.data.length > 0) {
    businesstypeTree.value = response.data;
  }
};
const column = [
  {
    name: "projectName",
    label: "项目名称",
    inSearch: true,
    valueType: "input",
  },
  { name: "projectId", label: "项目编号" },
  {
    name: "businessName",
    label: "业务类型",
    inSearch: true,
    valueType: "cascader",
    options: businesstypeTree,
    propsExpandTrigger: {
      value: "id",
      label: "businessName",
      checkStrictly: true,
      children: "children",
      emitPath: false,
    },
  },
  {
    name: "projectCreateTime",
    label: "创建时间",
    inSearch: true,
    valueType: "datetime",
    slot: true,
  },
  { name: "createPerson", label: "创建人" },
  { name: "operation", slot: true, label: "操作" },
];
// 全部地区列表
const areaList = ref([]);
const getareaList = async () => {
  const response = await location();
  if (response.code === 200 && response.data.length > 0) {
    areaList.value = response.data;
  }
};
// 全部地区配置
const areaCodeprops = {
  label: "name",
  children: "rcDistrictList",
  value: "id",
  // checkStrictly: true,
};

// 根据id查询任务的单条数据
let ids;
// 详情
const getContract = async () => {
  let id = Number(route.query.id);
  const res = await contractDetail(id);
  if (res.code === 200 && res.data) {
    for (let key in form) {
      if (res.data[key]) {
        form[key] = res.data[key];
      }
    }
    if (
      route.query.name === "6" ||
      route.query.name === "3" ||
      route.query.name === "2" ||
      route.query.name === "5"
    ) {
      ids = res.data.projectId;
    }

    // 审批方式 res.data && res.data.dataCheckInfo && res.data.dataCheckInfo.checkType;
    form.processCheckBo.checkType =
      res.data &&
      res.data.dataCheckInfoBo &&
      res.data.dataCheckInfoBo.checkType;
    if (res.data.businessType) {
      let model = JSON.parse(res.data.businessType)[0];
      for(let i=0,len = model.length; i<len ; i++){
        if(i%2==0){
          model[i]=Number(model[i]);
        }
      }
      // 业务
      form.businessTypeList = model;
    }

    // 行业
    if (res.data.industry) {
      form.industry = JSON.parse(res.data.industry);
    }

    if (res.data.address) {
      // 所在地区
      form.address = JSON.parse(res.data.address);
    }

    form.isStamped = Number(res.data.isStamped);
    // 合同期限
    if (res.data && res.data.startTime && res.data.endTime) {
      contractDate.value = [res.data.startTime, res.data.endTime];
    }
    if (res.data.dataCheckInfoBo) {
      // 审批进度
      activities.value = res.data.dataCheckInfoBo.opinons;
      //  审批id
      form.processCheckHistoryId =
        res.data.dataCheckInfoBo.processCheckHistoryId;
    }
    if (route.query.name === "5") {
      // 审批意见
      if (
        res.data &&
        res.data.dataCheckInfoBo &&
        res.data.dataCheckInfoBo.myCheckOpinionBo
      ) {
        form.approvalOpinions =
          res.data.dataCheckInfoBo.myCheckOpinionBo.opinion;
        form.fileList = res.data.dataCheckInfoBo.myCheckOpinionBo.fileList;
      }

      // 审批附件
    }
  }
};
// 点此关联
const correlation = () => {
  dialogTableVisible.value = true; // 关联
  approvalData();
};
// 关联项目的列表
const pageNum = ref(1);
const pageSize = ref(10);
const total = ref(0);
let paramsSubmit;
const approvalData = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  };
  if (paramsSubmit) {
    for (let key in paramsSubmit) {
      if (paramsSubmit[key]) {
        params[key] = paramsSubmit[key];
      }
    }
  }
  const res = await approvalLists(params);
  if (res.code === 200 && res.rows.length >= 0) {
    form.gridData = res.rows;
    total.value = res.total;
  }
};
// 切换每页条数
const handleSizeChange = (valueSise) => {
  pageSize.value = valueSise;
  approvalData();
};
// 切换页码
const handleCurrentChange = (valuePage) => {
  pageNum.value = valuePage;
  approvalData();
};
// 点击查询
const onSubmit = (val) => {
  val.projectCreateTime = formatDate(val.projectCreateTime);
  paramsSubmit = val;
  approvalData();
};
// 点击重置
const reset = (val) => {
  val = "";
  approvalData();
};

// 点击其他按钮需要的回显
const handleEcho = async () => {
  let params = {
    id:
      route.query.name === "6" ||
      route.query.name === "3" ||
      route.query.name === "2" ||
      route.query.name === "5"
        ? ids
        : Number(route.query.id),
  };
  const res = await approvalQuery(params);

  if (res && typeof (res === "object")) {
    form.projectName = res.data.projectName;
    form.enterpriseName = res.data.enterpriseName;
    form.enterprisePhone = res.data.enterprisePhone;
    form.enterprisePerson = res.data.enterprisePerson;
    form.industry = JSON.parse(res.data.industry);
    form.projectProperty = res.data.projectProperty;
    form.approvalDept = JSON.parse(res.data.approvalDept);
    form.superviseDept = JSON.parse(res.data.superviseDept);
    form.priority = res.data.priority;
    form.projectId = res.data.proId;
    form.address = JSON.parse(res.data.address);

    //通过判断业务类型的，来显示上传文件框
    businessType.value = res.data.test;
    //ist.value = showFileUpload(res.data.test);

    form.projectBriefly = res.data.projectBriefly;
    form.projectRemark = res.data.projectRemark;
  }
  dialogTableVisible.value = false;
  flag.value = true;
};
// 是否关联项目
const flag = ref(false);
// 点此选择关联项目
const handleClick = async (row) => {
  let params = { id: row.proId };
  const res = await approvalQuery(params);
  if (res.code === 200 && typeof (res.data === "object")) {
    form.projectName = res.data.projectName;
    form.enterpriseName = res.data.enterpriseName;
    form.enterprisePhone = res.data.enterprisePhone;
    form.enterprisePerson = res.data.enterprisePerson;
    form.industry = JSON.parse(res.data.industry);
    form.projectProperty = res.data.projectProperty;
    form.approvalDept = JSON.parse(res.data.approvalDept);
    form.superviseDept = JSON.parse(res.data.superviseDept);
    form.priority = res.data.priority;
    form.projectId = res.data.proId;
    form.address = JSON.parse(res.data.address);

    //通过判断业务类型的，来显示上传文件框
    businessType.value = res.data.test;
    //ist.value = showFileUpload(res.data.test);

    form.projectBriefly = res.data.projectBriefly;
    form.projectRemark = res.data.projectRemark;
  }
  dialogTableVisible.value = false;
  flag.value = true;
};

//控制上传文件组件的显示
// const ist = ref('3');
// const showFileUpload=(e)=>{
//   //类型1为'a-j',类型2为'册'
//   //返回值示例：
//   // [
//   //   {
//   //       "type": "6,89",
//   //       "value": 1
//   //   },
//   //   {
//   //       "type": "[6,88],[6,90]",
//   //       "value": 2
//   //   }
//   // ]

//   //先判断类型1，再判断类型2，其它为3
//   let typedic1 = businessTypeDicData.filter(o=>{ if(o.value == 1) return o } );
//   let typedic2 = businessTypeDicData.filter(o=>{ if(o.value == 2) return o } );
//   let result = '3';
//   //进行业务类型的判断
//   if(e.length == 0){
//     return result;
//   }
//   e.forEach(function(item){
//     typedic1.filter(function(o){
//       let typearr = JSON.parse("["+ o.type +"]");
//       typearr.forEach(function(p){
//         if(p.length == 2 
//         && p.length == item.length 
//         && p[0] == item[0]
//         && p[1] == item[1]){
//           result = typedic1[0].value;
//         }
//         else if(p.length == 1 
//         && p.length == item.length 
//         && p[0] == item[0]){
//           result = typedic1[0].value;
//         }
//       });
//     });
//   });

//   if(result == '1'){
//     return result;
//   }
//   e.forEach(function(item){
//     typedic2.filter(function(o){
//       let typearr = JSON.parse("["+ o.type +"]");
//       typearr.forEach(function(p){
//         if(p.length == 2 
//         && p.length == item.length 
//         && p[0] == item[0]
//         && p[1] == item[1]){
//           result = typedic2[0].value;
//         }
//         else if(p.length == 1 
//         && p.length == item.length 
//         && p[0] == item[0]){
//           result = typedic2[0].value;
//         }
//       });
//     });
//   });

//   return result;
// }

// 审批人
const handleChooseapprover = (id) => {
  if (id) {
    form.processCheckBo.checkPeopleIds = id;
  }
};
// 抄送人
const handleChooseapproverCc = (id) => {
  if (id) {
    form.processCheckBo.copyFor = id;
  }
};
// 如果是编辑或成果交付则不用关联项目
if (route.query.id && route.query.taskId) {
  flag.value = true;
}

const startTime = ref();
const endTime = ref();
// 新建任务
const ruleFormRef = ref();
const submitForm = async (formEl) => {
  if (!flag.value) {
    ElMessage.error("请关联项目");
    return;
  }
  
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (contractDate.value && contractDate.value[0]) {
        startTime.value = contractDate.value[0];
      }
      if (contractDate.value && contractDate.value[1]) {
        endTime.value = contractDate.value[1];
      }
      
      let businessTypeList_ = [];
      for(let i=0,len = form.businessTypeList.length; i<len; i++){
        businessTypeList_.push(String(form.businessTypeList[i]));
      }
      
      if (route.query.name === "1") {
        let newArray = [];
        let userCcIds;
        let userIds;
        let requestPayload;
        if(form.processCheckBo.checkPeopleIds.length <= 0){
          ElMessage.error("请选择审批人");
          return;
        }
        form.businessTypeList = [businessTypeList_];
        if (form.processCheckBo.checkPeopleIds) {
          userIds = form.processCheckBo.checkPeopleIds.map((item) =>
            item.userId ? Number(item?.userId) : item
          );
        }
        if (form.processCheckBo.copyFor) {
          userCcIds = form.processCheckBo.copyFor.map((item) =>
            item.userId ? Number(item?.userId) : item
          );
        }

        if (form.processCheckBo.checkType === 1) {
          // 逐级审批 orderCheckPeopleInfoList
          // 使用 map 方法重构数组
          newArray = form.processCheckBo.checkPeopleIds.map((item, index) => {
            return {
              orderNum: index + 1,
              userId: item.userId ? Number(item?.userId) : item,
            };
          });
          requestPayload = {
            ...form,
            startTime: startTime.value,
            endTime: endTime.value,
            processCheckBo: {
              orderCheckPeopleInfoList: newArray, // 直接作为顶层属性
              copyFor: userCcIds, // 直接作为顶层属性
              checkType: form.processCheckBo.checkType,
            },
          };
        } else {
          requestPayload = {
            ...form,
            startTime: startTime.value,
            endTime: endTime.value,
            processCheckBo: {
              checkPeopleIds: userIds, // 设置新的 checkPeopleIds 属性值
              copyFor: userCcIds,
              checkType: form.processCheckBo.checkType,
            },
          };
        }

        const res = await addContractApi(requestPayload);

        if (res.code === 200) {
          ElMessage.success(res.msg);
          router.push({
            path: "/contract",
          });
        } else {
          ElMessage.success(res.msg);
        }
      } else if (route.query.name === "2") {
        let newArray = [];
        let userCcIds;
        let userIds;
        let requestPayload;
        if(form.processCheckBo.checkPeopleIds.length <= 0){
          ElMessage.error("请选择审批人");
          return;
        }
        form.businessTypeList = [businessTypeList_];
        if (form.processCheckBo.checkPeopleIds) {
          userIds = form.processCheckBo.checkPeopleIds.map((item) =>
            item.userId ? Number(item?.userId) : item
          );
        }
        if (form.processCheckBo.copyFor) {
          userCcIds = form.processCheckBo.copyFor.map((item) =>
            item.userId ? Number(item?.userId) : item
          );
        }

        if (form.processCheckBo.checkType === 1) {
          // 逐级审批 orderCheckPeopleInfoList
          // 使用 map 方法重构数组
          newArray = form.processCheckBo.checkPeopleIds.map((item, index) => {
            return {
              orderNum: index + 1,
              userId: item.userId ? Number(item?.userId) : item,
            };
          });
          requestPayload = {
            contractId: route.query.id,
            ...form,
            startTime: startTime.value,
            endTime: endTime.value,
            processCheckBo: {
              orderCheckPeopleInfoList: newArray, // 直接作为顶层属性
              copyFor: userCcIds, // 直接作为顶层属性
              checkType: form.processCheckBo.checkType,
            },
          };
        } else {
          requestPayload = {
            contractId: route.query.id,
            ...form,
            startTime: startTime.value,
            endTime: endTime.value,
            processCheckBo: {
              checkPeopleIds: userIds, // 设置新的 checkPeopleIds 属性值
              copyFor: userCcIds,
              checkType: form.processCheckBo.checkType,
            },
          };
        }

        const res = await updateContractApi(requestPayload);

        if (res.code === 200) {
          ElMessage.success(res.msg);
          router.push({
            path: "/contract",
          });
        } else {
          ElMessage.success(res.msg);
        }
      } else if (route.query.contractStatus) {
        //上传附件功能
        let params = {
          contractId: route.query.id,
          signTime: form.signTime,
          fileListAfter: form.fileListAfter,
        };
        const res = await uploadAttachments(params);
        if (res.code === 200) {
          ElMessage.success(res.msg);
          router.push({
            path: "/contract",
          });
        } else {
          ElMessage.success(res.msg);
        }
      } else {
        //审批
        let data = {
          checkOpinion: form.approvalOpinions,
          id: form.processCheckHistoryId,
          copyFor: form.processCheckBo.copyFor.map((item) => item.userId),
          keepCheckId: form.processCheckBo.checkPeopleIds.map(
            (item) => item.userId
          ),
          state: "1",
          fileList: form.fileList,
          keepCheck: keepCheck.value,
        };

        const res = await approvalProcessApi(data);
        if (res.code === 200) {
          ElMessage.success("审批通过");
          router.push({
            path: "/examine",
          });
        } else {
          ElMessage.error(res.msg);
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 取消
const resetForm = async (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  if (route.query.name !== "6") {
    router.go(-1);
  } else {
    let data = {
      checkOpinion: form.approvalOpinions,
      id: form.processCheckHistoryId,
      copyFor: form.processCheckBo.copyFor.map((item) => item.userId),
      keepCheckId: form.processCheckBo.checkPeopleIds.map(
        (item) => item.userId
      ),
      state: "0",
      fileList: form.fileList,
      keepCheck: keepCheck.value,
    };
    const res = await approvalProcessApi(data);
    if (res.code === 200) {
      ElMessage.success("审批已驳回");
      router.go(-1);
    }
  }
};



// let businessTypeDicData = [];
// //获取
// const getbusinessTypeDicData = async() => {
//   //类型1为'a-j',类型2为'册'
//   //返回值示例：
//   // [
//   //   {
//   //       "type": "6,89",
//   //       "value": 1
//   //   },
//   //   {
//   //       "type": "[6,88],[6,90]",
//   //       "value": 2
//   //   }
//   // ]
//   let response = await getbusinessTypeDic();
//   if (response.code === 200 && response.rows.length > 0) {
//     businessTypeDicData = response.rows;
//   } else {
//     console.log(err);
//   }

// }


let businessOptions = [];
const getBusinessOptions = async ()=> {
  const response = await getbusinessTypeList();
  if (response.code === 200 && response.data.length > 0) {
    businessOptions = response.data;
  }
}

onMounted(async () => {
  hasButton();
  form.amountUnit = unitsList[0].label;

  //await getbusinessTypeDicData();
  await businessTypeOptions();
  await getBusinessOptions();
  await getindustryDown();
  await getareaList();

  if (route.query.name !== "1") {
    await getContract();
    await handleEcho();
  }
  //   await getUser();
});
</script>
<style >
.custom-cascader {
  width: 100%; /* 确保组件宽度足够 */
}

.custom-cascader .el-input__inner {
  white-space: normal; /* 允许换行 */
  word-break: break-all; /* 长单词或 URL 地址会在任意字符处换行 */
}
</style>
<style scoped lang="scss">
.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 10px;
}
.container {
  padding: 20px;
}
.form-single-info {
  display: flex;
  justify-content: center;
}
.title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  h5 {
    font-weight: bold;
  }
}

.basic_attribute {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  align-items: center;
  div {
    width: 300px;
    line-height: 50px;
  }
}
</style>
